<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';

import {
  EditOutlined,
  FileSearchOutlined,
  ToTopOutlined,
} from '@ant-design/icons-vue';
import { storeToRefs } from 'pinia';
// import { createApp, defineComponent, h } from 'vue';
import { Modal } from 'ant-design-vue';

import { get1688ShopStatusList, getProductList, syncProductList } from '#/api';
import { useTable } from '#/hooks/useTable';
import {
  addressStore,
  auto1688stor,
  guanlianprdStore,
  link1688stor,
} from '#/store';

import ProductInfo from './components/productInfo/index.vue';
import UpBingGoods from './components/upBingGoods/index.vue';
import SupplyInfo from './supplyInfo.vue';

const statusOption = ref<any>([]);
function getShopStatus() {
  get1688ShopStatusList().then((res) => {
    statusOption.value = res;
    statusOption.value.push({
      name: '全部',
      status: '',
    });
  });
}
onMounted(() => {
  getShopStatus();
});
const address = addressStore();

const auto1688 = auto1688stor();
const link1688 = link1688stor();
const { nowSelectDyShop, bindShopList } = auto1688.auto1688; // bindShopList
const selectShop = ref<any>(nowSelectDyShop?.shopId);
const columns = [
  {
    title: '商品信息',
    dataIndex: 'productInfo',
    key: 'productInfo',
    width: 300,
    align: 'left',
  },
  {
    title: '店铺sku匹配度',
    dataIndex: 'shopSkuMatch',
    key: 'shopSkuMatch',
    width: 160,
    align: 'center',
    border: true,
  },
  {
    title: '货源信息',
    dataIndex: 'supplyInfo',
    key: 'supplyInfo',
    width: 400,
    align: 'left',
  },
  {
    title: '货源sku匹配度',
    dataIndex: 'skuMatch',
    key: 'skuMatch',
    width: 160,
    align: 'center',
  },
  {
    title: '退货地址',
    dataIndex: 'returnAddress',
    key: 'returnAddress',
    // width: 230,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
    fixed: 'right',
  },
];
const searchForm = reactive({
  platformCode: '',
  orderType: '',
  shopId: selectShop.value,
  shopName: '',
  dyOrderStatus: '',
  aliOrderStatus: '',
  goodsTitle: '',
  dyOrderId: '',
  productId: '',
  offerId: '',
  status: '',
});
const {
  tableData,
  page,
  loading,
  resetParams,
  getList,
  handleCurrentChange,
  handleSizeChange,
} = useTable({
  apiFn: getProductList,
  params: searchForm,
});
link1688.getList = getList;
// onMounted(() => {
//   getList();
// });
function syncProductListFu() {
  syncProductList({
    shopId: selectShop.value,
  }).then(() => {
    Modal.success({
      title: '提示',
      content: '商品列表正在后端同步，请稍后查询列表查看',
    });
  });
}
const guanlianprd = guanlianprdStore();
const { showaddimgstatus } = storeToRefs(guanlianprd);
function openUseLinkBox(params: any) {
  link1688.getDeteail(params);
  link1688.showIsLinkBindStatus = true;
}
function openshowAddUseImage(record: any) {
  // guanlianprd.$reset();
  guanlianprd.setShopData({
    shopName: record.shopName,
    shopId: record.shopId,
  });
  guanlianprd.setSelectGetImageItemsData([record]);
  showaddimgstatus.value = true;
}
const fieldNames = {
  label: 'shopName',
  value: 'shopId',
};
watch(selectShop, () => {
  searchForm.shopId = selectShop.value;
});

function setAddressFn(record: any) {
  address.openSeletctAddress(record);
}

const upBingGoodsState = ref(false);
</script>

<template>
  <div class="h-full p-4">
    <div class="mb-4">
      <a-form layout="inline">
        <a-form-item
          class="mb-2"
          label="商品来源店铺"
          style="margin-bottom: 5px"
        >
          <a-select
            v-model:value="selectShop"
            :field-names="fieldNames"
            :options="bindShopList.filter((item) => item.pType === 2)"
            style="width: 180px"
          />
        </a-form-item>
        <a-form-item class="mb-2" label="店铺商品ID">
          <a-input
            v-model:value="searchForm.productId"
            placeholder="请输入商品ID"
          />
        </a-form-item>
        <a-form-item class="mb-2" label="商品标题">
          <a-input
            v-model:value="searchForm.goodsTitle"
            placeholder="商品标题"
          />
        </a-form-item>
        <a-form-item class="mb-2" label="货源商品ID">
          <a-input
            v-model:value="searchForm.offerId"
            placeholder="请输入商品ID"
          />
        </a-form-item>
        <a-form-item class="mb-2" label="状态">
          <a-select
            v-model:value="searchForm.status"
            :field-names="{
              label: 'name',
              value: 'status',
            }"
            :options="statusOption"
            placeholder="铺货状态"
            style="width: 180px"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="resetParams">重置</a-button>
            <a-button type="primary" @click="getList">查询</a-button>
            <a-button type="primary" @click="syncProductListFu">
              同步商品列表
            </a-button>
          </a-space>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="upBingGoodsState = true">
            <template #icon>
              <ToTopOutlined />
            </template>
            上传关联货源
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-table
      :columns="columns"
      :data-source="tableData"
      :loading="loading"
      :pagination="{
        total: page.total,
        pageSize: page.pageSize,
        showSizeChanger: true,
        current: page.page,
        class: 'pr-14',

        pageSizeOptions: page.pageSizes,
        showTotal: (total: any, range: any) =>
          `${range[0]}-${range[1]} 总 ${total} 条`,
      }"
      :scroll="{ x: 'max-content' }"
      @change="
        (da: any) => {
          // console.log('change', da, size);
          if (da.pageSize !== page.pageSize) {
            handleSizeChange(da.pageSize);
            return;
          }
          handleCurrentChange(da.current);
        }
      "
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'productInfo'">
          <ProductInfo :item-data="record" />
        </template>
        <template v-if="column.key === 'shopSkuMatch'">
          <a-space align="center" direction="vertical">
            <a-tag
              :color="record.skuCount1688 === record.skuCount ? 'green' : 'red'"
              style="margin: 0"
            >
              {{ record.skuCount1688 }} / {{ record.skuCount }}
            </a-tag>
            <a-progress
              :percent="
                record.skuCount
                  ? Number(
                      ((record.skuCount1688 / record.skuCount) * 100).toFixed(),
                    )
                  : 100
              "
              :size="40"
              type="circle"
            />
          </a-space>
        </template>
        <template v-if="column.key === 'supplyInfo'">
          <SupplyInfo :item-data="record" @clear-cb="getList" />
        </template>
        <template v-if="column.key === 'skuMatch'">
          <a-space
            v-if="
              record.bindGoods1688List && record.bindGoods1688List.length > 0
            "
            direction="vertical"
          >
            <a-space
              v-for="item in record.bindGoods1688List"
              :key="item.offerId"
              align="center"
              class="h-20 justify-center"
              direction="vertical"
            >
              <a-tag
                :color="item.skuMatchCount > 0 ? 'green' : 'red'"
                style="margin: 0"
              >
                {{ item.skuMatchCount > 0 ? '已匹配' : '未匹配' }}
              </a-tag>
              <div v-if="item.skuMatchCount > 0">
                <span style="color: green">
                  {{ item.skuMatchCount }}
                </span>
                /
                <span>
                  {{ item.skuTotal }}
                </span>
              </div>
            </a-space>
          </a-space>
          <a-tag v-else color="orange" style="margin: 0">未关联货源</a-tag>
        </template>
        <template v-if="column.key === 'returnAddress'">
          <a-space
            v-if="
              record.bindGoods1688List && record.bindGoods1688List.length > 0
            "
            direction="vertical"
          >
            <a-space
              v-for="item in record.bindGoods1688List"
              :key="item.offerId"
              class="h-20 justify-center"
              direction="vertical"
            >
              <div>
                <a-tag
                  :color="item.aliSaleAddress ? 'green' : 'red'"
                  style="margin: 0"
                >
                  {{ item.aliSaleAddress ? '已关联' : '未关联' }}
                </a-tag>
              </div>
              <a-space>
                <a-tooltip :title="item.aliSaleAddress?.addressDetail">
                  <div v-if="item.aliSaleAddress" class="w-32 truncate">
                    {{ item.aliSaleAddress.addressDetail }}
                  </div>
                </a-tooltip>

                <a-button
                  size="small"
                  type="link"
                  @click="() => setAddressFn(item)"
                >
                  <template #icon>
                    <EditOutlined />
                  </template>
                  编辑
                </a-button>
              </a-space>
            </a-space>
          </a-space>
          <a-tag v-else color="orange" style="margin: 0">未关联货源</a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space direction="vertical">
            <a-button type="primary" @click="openUseLinkBox(record)">
              <template #icon>
                <EditOutlined />
              </template>
              编辑货源
            </a-button>
            <a-button type="primary" @click="openshowAddUseImage(record)">
              <template #icon>
                <FileSearchOutlined />
              </template>
              搜索同款
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <UpBingGoods v-model:visible="upBingGoodsState" />
  </div>
</template>
<!-- :product-id="recordData.productId"
:select-item="recordData"
:shop-data="{
  shopName: recordData.shopName,
  shopId: recordData.shopId,
}" -->
